package _05thread;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @description:
 * @author: 景天
 * @date: 2022/1/15 17:35
 **/

/*
写1个定时任务,3s的延迟后,每隔5s向文件中写入一行当前时间
 */
public class Work10 {
    public static void main(String[] args) throws IOException {
        // 创建定时器
        Timer timer = new Timer();
        //3s的延迟后,每隔5s 执行1次该任务
        timer.schedule(new MyTask(), 3000, 5000);
    }
}

// 定义定时任务 继承TimerTask
class MyTask extends TimerTask{

    @Override
    public void run() {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("a.txt",true);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf.format(new Date());
            fileWriter.write(date);
            fileWriter.write(System.lineSeparator());
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}